﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using System.Data.Objects.DataClasses;

namespace GeckoPhotos.Repository
{
    public class EFRepositoryBase<TKey, TModel> : IRepository<TKey, TModel>
        where TKey : IComparable
        where TModel : EntityObject
    {
        protected readonly ObjectSet<TModel> _objectSet;

        public EFRepositoryBase(ObjectSet<TModel> objectSet)
        {
            if (objectSet == null)
                throw new ArgumentNullException();

            _objectSet = objectSet;
        }

        IQueryable<TModel> IRepository<TKey, TModel>.Where(Func<TModel, bool> query)
        {
            return _objectSet.Where(query).AsQueryable();
        }

        TModel IRepository<TKey, TModel>.Single(Func<TModel, bool> query)
        {
            return _objectSet.Single(query);
        }

        IQueryable<TModel> IRepository<TKey, TModel>.All()
        {
            return _objectSet;
        }

        void IRepository<TKey, TModel>.Insert(TModel entity)
        {
            _objectSet.AddObject(entity);
            _objectSet.Context.SaveChanges();
        }

        void IRepository<TKey, TModel>.Update(TModel entity)
        {
            _objectSet.Context.SaveChanges();
        }

        void IRepository<TKey, TModel>.Remove(TModel entity)
        {
            // Attach it before we delete.  This will have no effect 
            //  on entities that are already attached, but will allow 
            //  "stub" objects (e.g. "var o = new Blah { BlahID = 1};" ) 
            //  to be passed for delete.
            _objectSet.Attach(entity);

            _objectSet.DeleteObject(entity);
            _objectSet.Context.SaveChanges();
        }

        protected IRepository<TKey, TModel> IRepository
        {
            get
            {
                return this;
            }
        }

    }
}